package com.lw.edu.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lw.commonutil.result.ResultCodeEnum;
import com.lw.edu.entity.Subject;
import com.lw.edu.entity.excel.SubjectData;
import com.lw.edu.service.SubjectService;
import com.lw.servicebase.exception.GuliException;

//spring不能管理此监听器
public class SubjectExcelListener extends AnalysisEventListener<SubjectData> {
    private SubjectService subjectService;
    public SubjectExcelListener(){}
    public SubjectExcelListener(SubjectService subjectService){
        this.subjectService=subjectService;
    }
    //读取excel内容，一行一行读取
    @Override
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {
        if (subjectData==null){
            throw new GuliException( ResultCodeEnum.DATA_ERROR );
        }
        //存入数据库
        //判断一级分类不能重复添加
        Subject subject = this.existOneSubject( subjectData.getOneSubjectName() );
        if (subject==null){//当为空时添加一级分类
            subject=new Subject();
            subject.setTitle( subjectData.getOneSubjectName() );
            subject.setParentId( "0" );
            subject.setSort( 0 );
            subjectService.save( subject );
        }
        //判断二级分类是否存在
        Subject twoSubject = this.existTwoSubject( subjectData.getTwoSubjectName(), subject.getId() );
        if (twoSubject==null){//当为空时添加
            twoSubject=new Subject();
            twoSubject.setSort( 1 );
            twoSubject.setParentId( subject.getId() );
            twoSubject.setTitle( subjectData.getTwoSubjectName() );
            subjectService.save( twoSubject );
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
    private Subject existOneSubject(String oneSubjectName){
        QueryWrapper<Subject> wrapper = new QueryWrapper<Subject>().eq( "title", oneSubjectName ).eq( "parent_id", "0" );
        Subject subject = subjectService.getOne( wrapper );
        return subject;
    }
    private Subject existTwoSubject(String oneSubjectName,String parentId){
        QueryWrapper<Subject> wrapper = new QueryWrapper<Subject>().eq( "title", oneSubjectName ).eq( "parent_id", parentId );
        Subject subject = subjectService.getOne( wrapper );
        return subject;
    }
}
